package main

import (
	"context"
	"embed"
	"io/fs"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"demo/internal/config"
	"demo/internal/web"

	log "github.com/sirupsen/logrus"
)

// const (
// 	LIVE_FS = true
// 	DEV     = true
// )

// var fileServer http.Handler

//go:embed all:dist
var content embed.FS

func main() {

	// createServer()

	config.Configure("./data")

	// dbcfg := config.DbCfg()
	syscfg := config.SysCfg()
	log.Infof("sysconfig: %+v", syscfg)
	createServer(syscfg)
	// v := os.Getenv("dbg_db.username")
	// log.Infof("db: %+v, sys: %+v,  env: %v", dbcfg, syscfg, v)

}

func createServer(syscfg config.SysConfig) {
	assets, err := fs.Sub(content, "dist")
	if err != nil {
		panic(err)
	}

	if syscfg.LiveFS {
		log.Info("use LIVE_FS")
		if syscfg.Dev {
			log.Info("use dev path: ./public")
			assets = os.DirFS("./public")
		} else {
			log.Info("use dist ./dist")
			assets = os.DirFS("./dist")
		}
	}

	if !syscfg.Dev {
		if _, err := assets.Open(".vite/manifest.json"); err != nil {
			panic(err)
		}
		if _, err := assets.Open("index.html"); err != nil {
			panic(err)
		}
	}

	h := web.CreateWebServer(assets, web.Config{Dev: syscfg.Dev})
	s := &http.Server{
		Addr:    ":8081",
		Handler: h,
	}

	// if err := s.ListenAndServe(); err != nil {
	// 	panic(err)
	// }

	go func() {
		if err := s.ListenAndServe(); err != nil {
			log.Fatal(err)
		}
		// log.Info("server start at: %s", s.Addr)
	}()

	// 创建系统信号通道
	q := make(chan os.Signal)
	signal.Notify(q, syscall.SIGINT, syscall.SIGTERM)
	<-q
	log.Infof("shutdown server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := s.Shutdown(ctx); err != nil {
		log.Infof("shutdown server error: %v", err)
	}

	log.Info("shutdown server completed")

}
